package com.github.cooker.monitor.core.utils;

import com.google.common.collect.Maps;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 18/1/2022 2:52 下午
 * 描述：
 *
 * @author grant
 */
public class HttpUtils {


    @SneakyThrows
    public static HttpResp post(String url) {
        HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        HttpResp result = new HttpResp();
        String resp = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8);
        result.setCode(con.getResponseCode());
//            result.setHeaders();
        result.setBody(resp);
        return result;
    }

    @SneakyThrows
    public static HttpResp post(String url, Map<String, String> headers, String body) {
        HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        headers.keySet().forEach(
                key->{
                    con.setRequestProperty(key, headers.get(key));
                }
        );
        try (OutputStream out = con.getOutputStream()) {
            out.write(body.getBytes());
            out.flush();
        }
        HttpResp result = new HttpResp();
        String resp = IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8);
        result.setCode(con.getResponseCode());
//            result.setHeaders();
        result.setBody(resp);
        return result;
    }

    public static HttpResp postJson(String url, String body) {
        Map<String, String> headers = Maps.newHashMap();
        headers.put("Content-Type", "application/json");
        return post(url, headers, body);
    }

    @Data
    @NoArgsConstructor
    public static class HttpResp {
        private int code;
        private String body;
        private Map<String, String> headers;

        public boolean isSuccess() {
            return code == HttpURLConnection.HTTP_OK;
        }
    }
}
